package book;

public class DeadLock implements Runnable{

	public String username;
	public Object lock1 = new Object();
	public Object lock2 = new Object();
	
	public void setName(String username) {

		this.username = username;
	}
	
	@Override
	public void run() {

		try {
			if("a".equals(username)){
				
				synchronized (lock1) {
				
					System.out.println("username:" + username);
					Thread.sleep(1000);
					synchronized (lock2) {
					
						System.out.println("按lock1-lock2代码顺序执行了");
					}
				}
			}else{
				
				synchronized (lock2) {
					
					System.out.println("username:" + username);
					Thread.sleep(1000);
					synchronized (lock1) {
						
						System.out.println("按lock2-lock1代码顺序执行了");
					}
				}
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) throws InterruptedException {
		
		DeadLock lock = new DeadLock();
		lock.setName("a");
		Thread t1 = new Thread(lock);
		t1.start();
		
		Thread.sleep(500);
		lock.setName("b");
		Thread t2 = new Thread(lock);
		t2.start();
	}
}
